using B.S.RbacData.Domain.Traceabilitys;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Write.API.Applications.Commands.Traceabilitys;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;

namespace B.S.RbacData.Write.API.Applications.Commandhandlters.Traceabilitys
{
    /// <summary>
    /// 生成QR码命令处理器
    /// </summary>
    public class GenerateQRCodeCommandHandlter : IRequestHandler<GenerateQRCodeCommand, ApiResult<List<string>>>
    {
        private readonly DataDbcontext _dbContext;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ILogger<GenerateQRCodeCommandHandlter> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public GenerateQRCodeCommandHandlter(
            DataDbcontext dbContext,
            IHttpContextAccessor httpContextAccessor,
            ILogger<GenerateQRCodeCommandHandlter> logger)
        {
            _dbContext = dbContext;
            _httpContextAccessor = httpContextAccessor;
            _logger = logger;
        }

        /// <summary>
        /// 处理生成QR码命令
        /// </summary>
        public async Task<ApiResult<List<string>>> Handle(GenerateQRCodeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证产品是否存在
                var product = await _dbContext.Products
                    .FirstOrDefaultAsync(p => p.ID == request.ProductId && !p.IsDeleted, cancellationToken);

                if (product == null)
                {
                    return new ApiResult<List<string>>
                    {
                        code =ResultEnumCode.NotFind,
                        message = "产品不存在",
                        data = null
                    };
                }

                // 获取当前用户ID
                var userId = _httpContextAccessor.HttpContext?.User.FindFirstValue(ClaimTypes.NameIdentifier);
                if (string.IsNullOrEmpty(userId))
                {
                    return new ApiResult<List<string>>
                    {
                        code = ResultEnumCode.error,
                        message = "未获取到用户信息",
                        data = null
                    };
                }

                // 生成QR码
                var qrCodes = new List<QRCodeModel>();
                var qrCodeIds = new List<string>();
                var now = DateTime.Now;
                var batchNumber = $"{product.ProductionBatch}-{now:yyyyMMddHHmmss}";

                for (int i = 0; i < request.Quantity; i++)
                {
                    var uniqueCode = Guid.NewGuid().ToString("N");
                    qrCodeIds.Add(uniqueCode);

                    qrCodes.Add(new QRCodeModel
                    {
                        ProductId = request.ProductId,
                        UniqueCode = uniqueCode,
                        GeneratedDate = now,
                        IsUsed = false,
                        BatchNumber = batchNumber,
                        CreateTime = now,
                        CreateUserId = int.Parse(userId),
                        IsDeleted = false
                    });
                }

                // 保存到数据库
                await _dbContext.QRCodes.AddRangeAsync(qrCodes, cancellationToken);
                await _dbContext.SaveChangesAsync(cancellationToken);

                return new ApiResult<List<string>>
                {
                    code = ResultEnumCode.Ok,
                    message = "生成成功",
                    data = qrCodeIds
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成QR码时发生错误");
                return new ApiResult<List<string>>
                {
                    code =ResultEnumCode.fails,
                    message = "生成QR码时发生错误：" + ex.Message,
                    data = null
                };
            }
        }
    }
} 